import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import plcService from '../services/plcService';

// 格式化北京时间显示
const formatToBeijingTime = (timestamp) => {
  if (!timestamp) return 'N/A';
  const date = new Date(timestamp);
  const beijingTime = new Date(date.getTime() + 8 * 60 * 60 * 1000);
  return beijingTime.toISOString().replace('T', ' ').substring(0, 19);
};

// 格式化耗时显示
const formatDuration = (duration) => {
  if (duration === undefined) return 'N/A';
  if (duration < 1000) {
    return `${duration}ms`;
  } else {
    return `${(duration / 1000).toFixed(2)}s`;
  }
};

export default function PLCQueue() {
  const [logs, setLogs] = useState([]);
  const [queueStatus, setQueueStatus] = useState(null);
  const [queueHistory, setQueueHistory] = useState([]);
  const [activeTab, setActiveTab] = useState('status'); // 'status', 'history'
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  
  // 添加日志
  const addLog = (message) => {
    setLogs(prev => [...prev, `${new Date().toLocaleTimeString()}: ${message}`]);
  };
  
  // 清除日志
  const clearLogs = () => {
    setLogs([]);
  };
  
  // 获取队列状态
  const fetchQueueStatus = async () => {
    try {
      setLoading(true);
      setError(null);
      const status = await plcService.getQueueStatus();
      setQueueStatus(status);
      addLog(`获取队列状态成功: 队列长度 ${status.queueLength}`);
    } catch (err) {
      console.error('获取队列状态失败:', err);
      setError(err.message);
      addLog(`❌ 获取队列状态失败: ${err.message}`);
    } finally {
      setLoading(false);
    }
  };
  
  // 获取队列历史记录
  const fetchQueueHistory = async () => {
    try {
      const history = await plcService.getQueueHistory();
      setQueueHistory(history);
      addLog(`获取队列历史记录成功: ${history.length} 条记录`);
    } catch (err) {
      console.error('获取队列历史记录失败:', err);
      addLog(`❌ 获取队列历史记录失败: ${err.message}`);
    }
  };
  
  // 定时获取队列状态和历史记录
  useEffect(() => {
    const fetchData = async () => {
      if (activeTab === 'status') {
        await fetchQueueStatus();
      } else if (activeTab === 'history') {
        await fetchQueueHistory();
      }
    };
    
    // 立即获取一次数据
    fetchData();
    
    // 每5秒刷新一次
    const interval = setInterval(fetchData, 5000);
    
    return () => clearInterval(interval);
  }, [activeTab]);
  
  return (
    <div style={{ width: '100vw', height: '100vh', position: 'relative' }}>
      

      {/* 标签页切换 */}
      <div style={{
        position: 'fixed',
        top: '170px',
        left: '50%',
        transform: 'translateX(-50%)',
        width: '80%',
        maxWidth: '1000px',
        display: 'flex',
        gap: '2px',
        zIndex: 900
      }}>
        <button
          onClick={() => setActiveTab('status')}
          style={{
            flex: 1,
            padding: '12px',
            background: activeTab === 'status' ? '#2196F3' : '#555',
            color: 'white',
            border: 'none',
            cursor: 'pointer',
            fontWeight: 'bold',
            borderTopLeftRadius: '5px',
            borderTopRightRadius: activeTab === 'status' ? '0' : '5px'
          }}
        >
          当前状态
        </button>
        <button
          onClick={() => setActiveTab('history')}
          style={{
            flex: 1,
            padding: '12px',
            background: activeTab === 'history' ? '#2196F3' : '#555',
            color: 'white',
            border: 'none',
            cursor: 'pointer',
            fontWeight: 'bold',
            borderTopLeftRadius: activeTab === 'history' ? '0' : '5px',
            borderTopRightRadius: '5px'
          }}
        >
          历史记录
        </button>
      </div>

      {/* 内容显示区域 */}
      <div style={{
        position: 'fixed',
        top: '180px',
        left: '50%',
        transform: 'translateX(-50%)',
        width: '80%',
        maxWidth: '1000px',
        background: 'rgba(30, 30, 30, 0.9)',
        padding: '20px',
        borderRadius: '10px',
        border: '2px solid #2196F3',
        backdropFilter: 'blur(10px)',
        maxHeight: 'calc(100vh - 200px)',
        overflowY: 'auto'
      }}>
        {activeTab === 'status' ? (
          // 当前状态标签页内容
          <>
            {loading ? (
              <div style={{ textAlign: 'center', color: '#fff', fontSize: '18px' }}>
                🔄 正在加载队列状态...
              </div>
            ) : error ? (
              <div style={{ textAlign: 'center', color: '#f44336', fontSize: '18px' }}>
                ❌ {error}
              </div>
            ) : queueStatus ? (
              <div>
                <h2 style={{ color: '#fff', textAlign: 'center' }}>PLC队列状态信息</h2>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(200px, 1fr))', gap: '20px', marginTop: '20px' }}>
                  <div style={{ background: '#4CAF50', padding: '15px', borderRadius: '5px', textAlign: 'center' }}>
                    <div style={{ fontSize: '24px', fontWeight: 'bold' }}>{queueStatus.queueLength}</div>
                    <div>待处理任务数</div>
                  </div>
                  <div style={{ background: queueStatus.processing ? '#FF9800' : '#4CAF50', padding: '15px', borderRadius: '5px', textAlign: 'center' }}>
                    <div style={{ fontSize: '24px', fontWeight: 'bold' }}>
                      {queueStatus.processing ? '处理中' : '空闲'}
                    </div>
                    <div>处理状态</div>
                  </div>
                </div>
                
                <h3 style={{ color: '#fff', marginTop: '30px' }}>待处理任务列表</h3>
                {queueStatus.pendingTasks && queueStatus.pendingTasks.length > 0 ? (
                  <div style={{ marginTop: '15px' }}>
                    <table style={{ width: '100%', borderCollapse: 'collapse', color: '#fff' }}>
                      <thead>
                        <tr style={{ background: '#2196F3' }}>
                          <th style={{ padding: '10px', textAlign: 'left' }}>任务类型</th>
                          <th style={{ padding: '10px', textAlign: 'left' }}>任务详情</th>
                          <th style={{ padding: '10px', textAlign: 'left' }}>添加时间</th>
                        </tr>
                      </thead>
                      <tbody>
                        {queueStatus.pendingTasks.map((task, index) => (
                          <tr key={index} style={{ background: index % 2 === 0 ? '#444' : '#333' }}>
                            <td style={{ padding: '10px' }}>{task.type}</td>
                            <td style={{ padding: '10px' }}>
                              {task.variables && `变量: ${Array.isArray(task.variables) ? task.variables.join(', ') : task.variables}`}
                              {task.groupId && `分组: ${task.groupId}`}
                              {task.variable && `变量: ${task.variable}`}
                              {task.value !== undefined && `, 值: ${task.value}`}
                            </td>
                            <td style={{ padding: '10px' }}>{formatToBeijingTime(task.timestamp)}</td>
                          </tr>
                        ))}
                      </tbody>
                    </table>
                  </div>
                ) : (
                  <div style={{ textAlign: 'center', color: '#aaa', marginTop: '15px' }}>
                    当前没有待处理的任务
                  </div>
                )}
              </div>
            ) : (
              <div style={{ textAlign: 'center', color: '#fff', fontSize: '18px' }}>
                无法获取队列状态信息
              </div>
            )}
          </>
        ) : (
          // 历史记录标签页内容
          <div>
            <h2 style={{ color: '#fff', textAlign: 'center' }}>PLC队列历史记录</h2>
            {queueHistory && queueHistory.length > 0 ? (
              <div style={{ marginTop: '15px' }}>
                <table style={{ width: '100%', borderCollapse: 'collapse', color: '#fff' }}>
                  <thead>
                    <tr style={{ background: '#2196F3' }}>
                      <th style={{ padding: '10px', textAlign: 'left' }}>任务类型</th>
                      <th style={{ padding: '10px', textAlign: 'left' }}>任务详情</th>
                      <th style={{ padding: '10px', textAlign: 'left' }}>状态</th>
                      <th style={{ padding: '10px', textAlign: 'left' }}>耗时</th>
                      <th style={{ padding: '10px', textAlign: 'left' }}>时间</th>
                    </tr>
                  </thead>
                  <tbody>
                    {queueHistory.map((task, index) => (
                      <tr key={index} style={{ background: index % 2 === 0 ? '#444' : '#333' }}>
                        <td style={{ padding: '10px' }}>{task.type || '未知'}</td>
                        <td style={{ padding: '10px' }}>
                          {task.variables && `变量: ${Array.isArray(task.variables) ? task.variables.join(', ') : task.variables}`}
                          {task.groupId && `分组: ${task.groupId}`}
                          {task.variable && `变量: ${task.variable}`}
                          {task.value !== undefined && `, 值: ${task.value}`}
                        </td>
                        <td style={{ padding: '10px' }}>
                          <span style={{
                            padding: '3px 8px',
                            borderRadius: '3px',
                            backgroundColor: task.status === 'completed' ? '#4CAF50' : '#f44336'
                          }}>
                            {task.status === 'completed' ? '完成' : '失败'}
                          </span>
                        </td>
                         <td style={{ padding: '10px' }}>{formatDuration(task.duration)}</td>
                        <td style={{ padding: '10px' }}>{formatToBeijingTime(task.timestamp)}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            ) : (
              <div style={{ textAlign: 'center', color: '#aaa', marginTop: '15px' }}>
                暂无历史任务记录
              </div>
            )}
          </div>
        )}
      </div>
    </div>
  );
}